import Vue from 'vue'
import VueRouter from 'vue-router'

// 解决路由重复点击报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },

  { path: '/home', meta: { activeNum: 0, isShowTabbar: true, scrollTop: 0 }, component: () => import('../views/Home.vue') },

  { path: "/SearchPopup", component: () => import('../views/SearchPopup.vue'), meta: { scrollTop: 0 } },

  { path: '/topic', name: 'Topic', meta: { activeNum: 1, isShowTabbar: true }, component: () => import('../views/Topic.vue') },

  { path: '/category', name: 'Category', meta: { activeNum: 2, isShowTabbar: true }, component: () => import('../views/Category.vue'), children: [] },

  { path: '/cart', name: 'Cart', meta: { activeNum: 3, isShowTabbar: true }, component: () => import('../views/Cart.vue') },

  { path: '/user', name: 'User', meta: { activeNum: 4, isShowTabbar: true }, component: () => import('../views/User.vue') },

  { path: '/pruductDetail', name: 'PruductDetail', component: () => import('../views/PruductDetail.vue') },

  { path: '/pinPaiZhiZao', name: 'PinPaiZhiZao', component: () => import('../views/PinPaiZhiZao.vue') },

  { path: '/categoryTabLan', name: 'CategoryTabLan', component: () => import('../views/CategoryTabLan.vue'), meta: { scrollTop: 0 } }
]

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { x: 0, y: 0 }
  }
})

// 为路由对象添加导航守卫
router.beforeEach((to, from, next) => {
  //获取token
  const tokenStr = localStorage.getItem('token')
  if (to.path === '/cart') {
    // 没有token就强制跳转到登录页
    if (tokenStr) {
      next()
    } else {
      Vue.prototype.$toast('请先登录！')
      setTimeout(() => {
        next('/user')
      }, 1000)
    }
  } else {
    next()
  }
})

// 全局后置钩子
router.afterEach((to, from) => {
  if (to.meta.scrollTop) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.scrollTop)
    }, 0)
  }
})

export default router
